var express = require('express');
// const { query_cat } = require('../../../../node-day04-2/02-code/myshop/db/db');
var router = express.Router();
var queryWithPromise = require("../db/db").queryWithPromise
var query_cat = require("../db/db").query_cat

/* GET users listing. */
router.get('/getmenu', async function(req, res, next) {
    if (req.session.user_id) {
        try {
            // res.send('respond with a resource');
            // 获取用户对应的菜单项
            // 根据session获取用户id
            let user_id = req.session.user_id
                // 根据用户id去数据库获取对应的角色
            let sql = "select * from user_role where user_id = ?"
            let menus = [];
            // 改造第一个query
            let { results } = await queryWithPromise(sql, [user_id]);
            console.log(results)
                // 获取角色id
            let role_id = results[0].role_id
                // console.log(role_id)
                // 根据角色id搜索菜单id
            let sql_menus = "select * from role_menu where role_id = ?";
            // 改造第二个query
            let res_menus = await queryWithPromise(sql_menus, [role_id])
            let res2 = res_menus.results
            console.log(res2)
                /*  let cat_ids = []
                 res2.map(v => {
                         // 获取角色所对应的所有菜单id
                         cat_ids.push(v.cat_id)
                     }) */
                // 对cat_ids遍历
            for (let i = 0; i < res2.length; i++) {
                // 获取对应的菜单id即cat_res
                let cat_res = await query_cat(res2[i].cat_id)
                    // console.log(cat_res)
                menus.push({
                    cat_id: cat_res[0].cat_id,
                    cat_name: cat_res[0].cat_name,
                    cat_pid: cat_res[0].cat_pid
                })
            }
            console.log(menus)
                // 返回响应数据
            res.json({
                code: 1,
                data: menus,
            })

        } catch (err) {
            res.json({
                code: -1,
                msg: err
            })
        }
    } else {
        res.json({
            code: -1,
            msg: "请先登录"
        })
    }
});

module.exports = router;